<template>
  <div class="ai-chat-container">
    <!-- 侧边栏 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <el-button type="primary" @click="createNewConversation" icon="el-icon-plus">
          新建对话
        </el-button>
      </div>
      
      <div class="conversation-list">
        <div 
          v-for="conversation in conversations" 
          :key="conversation.id"
          class="conversation-item"
          :class="{ active: currentConversationId === conversation.id }"
          @click="selectConversation(conversation.id)"
        >
          <div class="conversation-title">{{ conversation.title }}</div>
          <div class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</div>
          <el-button 
            type="text" 
            icon="el-icon-delete" 
            @click.stop="archiveConversation(conversation.id)"
            class="delete-btn"
          />
        </div>
      </div>
    </div>
    
    <!-- 主聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
        <h3>{{ currentConversationTitle }}</h3>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="message in messages" 
          :key="message.id"
          class="message-item"
          :class="message.messageType"
        >
          <div class="message-avatar">
            <i :class="message.messageType === 'USER' ? 'el-icon-user' : 'el-icon-service'"></i>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.createTime) }}</div>
            <div v-if="message.fileId" class="message-file">
              <i class="el-icon-paperclip"></i>
              <span>附件</span>
            </div>
          </div>
        </div>
        
        <!-- 加载中状态 -->
        <div v-if="isLoading" class="message-item ASSISTANT">
          <div class="message-avatar">
            <i class="el-icon-service"></i>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-toolbar">
          <el-upload
            :action="uploadUrl"
            :data="{ userId: currentUserId }"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            accept="image/*,text/*,.pdf"
          >
            <el-button type="text" icon="el-icon-paperclip">附件</el-button>
          </el-upload>
        </div>
        
        <div class="input-area">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            @keydown.ctrl.enter="sendMessage"
            :disabled="isLoading"
          />
          <el-button 
            type="primary" 
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  sendChatMessage, 
  sendChatMessageStream,
  getConversations, 
  getConversationMessages, 
  archiveConversation,
  uploadFile 
} from '@/api/ai/chat'
import { getToken } from '@/utils/auth'

export default {
  name: 'AiChat',
  data() {
    return {
      conversations: [],
      messages: [],
      currentConversationId: null,
      currentConversationTitle: 'AI助手',
      currentUserId: '',
      inputMessage: '',
      isLoading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/ai/chat/upload',
      currentStream: null
    }
  },
  mounted() {
    this.initChat()
  },
  methods: {
    async initChat() {
      // 获取当前用户ID（这里需要根据实际的用户信息获取）
      this.currentUserId = this.getCurrentUserId()
      await this.loadConversations()
    },
    
    getCurrentUserId() {
      // 这里需要根据实际的用户认证方式获取用户ID
      // 暂时使用固定值，实际项目中应该从token或store中获取
      return 'user001'
    },
    
    async loadConversations() {
      try {
        const response = await getConversations(this.currentUserId)
        if (response.code === 200) {
          this.conversations = response.data || []
          if (this.conversations.length > 0 && !this.currentConversationId) {
            this.selectConversation(this.conversations[0].id)
          }
        }
      } catch (error) {
        this.$message.error('加载会话列表失败')
        console.error(error)
      }
    },
    
    async selectConversation(conversationId) {
      this.currentConversationId = conversationId
      const conversation = this.conversations.find(c => c.id === conversationId)
      if (conversation) {
        this.currentConversationTitle = conversation.title
      }
      await this.loadMessages(conversationId)
    },
    
    async loadMessages(conversationId) {
      try {
        const response = await getConversationMessages(conversationId)
        if (response.code === 200) {
          this.messages = response.data || []
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        this.$message.error('加载消息历史失败')
        console.error(error)
      }
    },
    
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) {
        return
      }
      
      this.isLoading = true
      const message = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息到界面
      const userMessage = {
        id: Date.now(),
        messageType: 'USER',
        content: message,
        createTime: new Date(),
        userId: this.currentUserId
      }
      this.messages.push(userMessage)
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      // 添加AI消息占位符
      const aiMessage = {
        id: Date.now() + 1,
        messageType: 'ASSISTANT',
        content: '',
        createTime: new Date(),
        userId: this.currentUserId,
        isStreaming: true
      }
      this.messages.push(aiMessage)
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      try {
        const requestData = {
          message: message,
          userId: this.currentUserId,
          conversationId: this.currentConversationId,
          createNewConversation: !this.currentConversationId
        }
        
        // 使用流式响应
        console.log('开始发送流式请求，requestData:', requestData)
        console.log('AI消息对象:', aiMessage)
        
        const stream = sendChatMessageStream(
          requestData,
          (data) => {
            console.log('完整聊天页面收到流式数据:', data, '类型:', typeof data)
            if (typeof data === 'object' && data.type === 'conversation') {
              // 更新会话ID
              console.log('更新会话ID:', data.conversationId)
              this.currentConversationId = data.conversationId
            } else if (typeof data === 'string') {
              // 更新AI消息内容
              console.log('更新AI消息内容:', data)
              console.log('当前messages数组长度:', this.messages.length)
              console.log('查找的aiMessage.id:', aiMessage.id)
              
              const messageIndex = this.messages.findIndex(msg => msg.id === aiMessage.id)
              console.log('找到的消息索引:', messageIndex)
              
              if (messageIndex !== -1) {
                const currentContent = this.messages[messageIndex].content
                const newContent = currentContent + data
                console.log('当前内容:', currentContent, '新内容:', newContent)
                
                // 使用Vue.set确保响应式更新
                this.$set(this.messages[messageIndex], 'content', newContent)
                console.log('修改后的消息:', this.messages[messageIndex])
                console.log('修改后的messages数组:', this.messages)
                
                this.$nextTick(() => {
                  this.scrollToBottom()
                })
              } else {
                console.error('未找到对应的AI消息对象')
                console.error('当前所有消息ID:', this.messages.map(m => m.id))
              }
            }
          },
          (error) => {
            console.error('流式响应错误:', error)
            this.$message.error('发送消息失败: ' + error.message)
            const messageIndex = this.messages.findIndex(msg => msg.id === aiMessage.id)
            if (messageIndex !== -1) {
              this.$set(this.messages[messageIndex], 'content', '发送失败: ' + error.message)
              this.$set(this.messages[messageIndex], 'isStreaming', false)
            }
          },
          () => {
            console.log('流式响应完成')
            // 完成
            const messageIndex = this.messages.findIndex(msg => msg.id === aiMessage.id)
            if (messageIndex !== -1) {
              this.$set(this.messages[messageIndex], 'isStreaming', false)
            }
            this.loadConversations() // 重新加载会话列表
          }
        )
        
        // 保存流对象以便取消
        this.currentStream = stream
        
      } catch (error) {
        this.$message.error('发送消息失败')
        console.error(error)
        const messageIndex = this.messages.findIndex(msg => msg.id === aiMessage.id)
        if (messageIndex !== -1) {
          this.$set(this.messages[messageIndex], 'content', '发送失败')
          this.$set(this.messages[messageIndex], 'isStreaming', false)
        }
      } finally {
        this.isLoading = false
      }
    },
    
    async createNewConversation() {
      this.currentConversationId = null
      this.currentConversationTitle = '新对话'
      this.messages = []
    },
    
    async archiveConversation(conversationId) {
      try {
        await this.$confirm('确定要归档这个对话吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await archiveConversation(conversationId)
        if (response.code === 200) {
          this.$message.success('对话已归档')
          await this.loadConversations()
          
          // 如果归档的是当前对话，切换到其他对话
          if (conversationId === this.currentConversationId) {
            if (this.conversations.length > 0) {
              this.selectConversation(this.conversations[0].id)
            } else {
              this.createNewConversation()
            }
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('归档对话失败')
          console.error(error)
        }
      }
    },
    
    beforeUpload(file) {
      const isValidType = file.type.startsWith('image/') || 
                         file.type.startsWith('text/') || 
                         file.type === 'application/pdf'
      if (!isValidType) {
        this.$message.error('只支持图片、文本和PDF文件')
        return false
      }
      
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }
      
      return true
    },
    
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success('文件上传成功')
        // 这里可以将文件信息添加到消息中
      } else {
        this.$message.error(response.message || '文件上传失败')
      }
    },
    
    handleUploadError(error) {
      this.$message.error('文件上传失败')
      console.error(error)
    },
    
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    },
    
    formatMessage(content) {
      if (!content) return ''
      // 简单的换行处理
      return content.replace(/\n/g, '<br>')
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  height: calc(100vh - 84px);
  background: #f5f5f5;
}

.chat-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  position: relative;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #f8f9fa;
}

.conversation-item.active {
  background-color: #e3f2fd;
  border-right: 3px solid #2196f3;
}

.conversation-title {
  font-weight: 500;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: 12px;
  color: #999;
}

.delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 0.2s;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  background: white;
}

.chat-header h3 {
  margin: 0;
  color: #333;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message-item.USER {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
  flex-shrink: 0;
}

.message-item.USER .message-avatar {
  background: #2196f3;
  color: white;
}

.message-item.ASSISTANT .message-avatar {
  background: #4caf50;
  color: white;
}

.message-content {
  max-width: 70%;
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.message-item.USER .message-content {
  background: #2196f3;
  color: white;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.message-item.USER .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.message-file {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.typing-indicator {
  display: flex;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  margin-right: 4px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.chat-input {
  border-top: 1px solid #e6e6e6;
  padding: 20px;
  background: white;
}

.input-toolbar {
  margin-bottom: 10px;
}

.input-area {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.input-area .el-textarea {
  flex: 1;
}

/* 滚动条样式 */
.conversation-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.conversation-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.conversation-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.conversation-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
